package com.dehui.traders.ui.main;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;

import com.dehui.traders.BR;
import com.dehui.traders.R;
import com.dehui.traders.app.AppApplication;
import com.dehui.traders.bean.UserInfo;
import com.dehui.traders.databinding.ActivityMainBinding;
import com.dehui.traders.utils.UserHelp;
import com.pgyersdk.javabean.AppBean;
import com.pgyersdk.update.PgyUpdateManager;
import com.pgyersdk.update.UpdateManagerListener;

import java.util.HashSet;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import me.goldze.mvvmhabit.base.BaseActivity;
import me.goldze.mvvmhabit.utils.ToastUtils;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;

import static com.pgyersdk.update.UpdateManagerListener.startDownloadTask;

public class MainActivity extends BaseActivity<ActivityMainBinding, MainViewModel> {

    public static MainActivity context;
    public static boolean isRepeat = true;
    private AppBean appBean;
    private static final int MY_PERMISSION_REQUEST_CODE = 10000;

    @Override
    public int initContentView() {
        return R.layout.activity_main;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public MainViewModel initViewModel() {
        return new MainViewModel(this, this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        initToolbar();

        String registrationID = JPushInterface.getRegistrationID(context);
        JPushInterface.setAlias(context, 1, registrationID);

        PgyUpdateManager.register(MainActivity.this,
                new UpdateManagerListener() {

                    @Override
                    public void onUpdateAvailable(final String result) {
                        appBean = getAppBeanFromString(result);
                        if (appBean == null)
                            return;
                        String versionCode = appBean.getVersionCode();
                        if (Integer.valueOf(versionCode) > AppApplication.getVersionCode()){
                            showUpdateDialog();
                        }
                    }

                    @Override
                    public void onNoUpdateAvailable() {
                        toUpdate();
                    }
                });

    }

    private void showUpdateDialog() {
        new AlertDialog.Builder(MainActivity.this)
                .setTitle("发现新版本")
                .setMessage(appBean.getReleaseNote())
                .setNegativeButton("取消",null)
                .setPositiveButton(
                        "立即更新",
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                toUpdate();
                            }
                        }
                ).show();
    }

    private void toUpdate() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            checkPermission();
        }
    }

    private void checkPermission() {
        boolean isAllGranted = checkPermissionAllGranted(
                new String[]{
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                }
        );

        if (!isAllGranted) {
            ActivityCompat.requestPermissions(this,
                    new String[]{
                            Manifest.permission.WRITE_EXTERNAL_STORAGE
                    },
                    MY_PERMISSION_REQUEST_CODE
            );

            return;
        } else {
            toUpateApk();
        }
    }

    private void toUpateApk() {
        if (appBean == null)
            return;
        String versionCode = appBean.getVersionCode();
        if (Integer.valueOf(versionCode) > AppApplication.getVersionCode()){
            startDownloadTask(
                    MainActivity.this,
                    appBean.getDownloadURL());
        }
    }


    private boolean checkPermissionAllGranted(String[] permissions) {
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == MY_PERMISSION_REQUEST_CODE) {
            boolean isAllGranted = true;
            if (grantResults.length > 0) {
                if (isAllGranted) {
                    toUpateApk();
                } else {
                    ToastUtils.showShort("需要打开存储权限，否则有部分功能不能正常使用");
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        context = null;
    }

    private void initToolbar() {
        setSupportActionBar(binding.mainToolbar);
    }


    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
    }

}
